package model

import (
	"gin-project/utils"
	"gin-project/utils/errmsg"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"mime/multipart"
	"strconv"
)

type User struct {
	gorm.Model
	UserName     string `json:"username"`
	PassWord     string `json:"pass_word"`
	Sex          int    `json:"sex"`
	Phone        string `json:"phoneNum"`
	Email        string `json:"email"`
	Birth        string `json:"birth"`
	Introduction string `json:"introduction"`
	Location     string `json:"location"`
	Avatar       string `json:"avatar"`
}

func (User) TableName() string {
	return "user"
}

// 密码加密
func encryption(password string) string {
	hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) // 加密处理
	return string(hash)
}

// 密码解密
func decrypt(encryptPwd string, password string) error {
	return bcrypt.CompareHashAndPassword([]byte(encryptPwd), []byte(password))
}

// 检查用户名和密码
func CheckUsernameAndPwd(username string, password string) int {
	var user User
	err := db.Where("user_name = ?", username).First(&user).Error
	if err != nil && gorm.ErrRecordNotFound != nil {
		return errmsg.USER_NAME_OR_PWD_FAILED
	}

	err = decrypt(user.PassWord, password)
	if err != nil {
		return errmsg.USER_NAME_OR_PWD_FAILED
	}
	return errmsg.SUCCESS
}

// 检查用户名是否存在
func CheckUsername(username string) int {
	var user User
	err := db.Where("user_name = ?", username).First(&user).Error
	if err != nil && gorm.ErrRecordNotFound != nil {
		return errmsg.SUCCESS
	}
	return errmsg.USER_USERNAME_USED
}

// 检查邮箱是否存在
func CheckEmail(email string) int {
	var user User
	err := db.Where("email = ?", email).First(&user).Error
	if err != nil && gorm.ErrRecordNotFound != nil {
		return errmsg.SUCCESS
	}
	return errmsg.USER_EMAIL_USED
}

// 增加用户
func InsertUser(user *User) int {
	pwd := encryption(user.PassWord)
	user.PassWord = pwd
	err := db.Create(&user).Error
	if err != nil {
		return errmsg.USER_REGISTER_FAILED
	}
	return errmsg.SUCCESS
}

// 查询所有用户
func SelectUserAll() ([]*User, int) {
	var users []*User
	err := db.Find(&users).Error
	if err != nil {
		return nil, errmsg.USER_SELECT_FAILED
	}
	return users, errmsg.SUCCESS
}

// 更新用户图片
func UpdateUserPic(file multipart.File, header *multipart.FileHeader) (string, int) {
	return utils.UploadFile(file, header.Size)
}

// 更新用户信息
func UpdateUser(m map[string]interface{}, id string) int {
	err := db.Model(&User{}).Where("id = ?", id).Updates(m).Error
	if err != nil {
		return errmsg.USER_UPDATE_FAILED
	}
	return errmsg.SUCCESS
}

// 根据id删除用户
func DeleteUserByID(id string) int {
	convID, _ := strconv.Atoi(id)
	err := db.Where("id = ?", convID).Delete(&User{}).Error
	if err != nil {
		return errmsg.USER_DELETE_FAILED
	}
	return errmsg.SUCCESS
}